package com.xj.interceptor;

import com.xj.model.Ticket;
import com.xj.model.User;
import com.xj.service.BrowerHolderService;
import com.xj.service.TicketService;
import com.xj.service.UserService;
import com.xj.utils.BrowerHolderUtils;
import com.xj.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 浏览器的使用者拦截器
 */
@Component
public class HostInfoInterceptor implements HandlerInterceptor {

  @Autowired
  private TicketService ticketService;

  @Autowired
  private UserService userService;

  @Autowired
  private BrowerHolderService browerHolderService;

  /**
   * 为浏览器注入host信息。
   * 初始化操作，將user存入threadLocal，方便后续操作
   *
   * 这里实现的功能是：记录密码的免密登录功能，上次登录了，只要没过期，下次直接进入系统
   * 技术方案：拦截器+Cookie+ticket过期时间+threadLocal<User>。
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String t = CookieUtils.getCookie("t", request);
    if (!StringUtils.isEmpty(t)) {
      Ticket ticket = ticketService.getTicket(t);
      if (ticket != null && ticket.getExpiredAt().after(new Date())) {
        User host = userService.getUser(ticket.getUserId());
        browerHolderService.setHostUser(host);
      }
    }
    return true;
  }
}
